<?php

namespace app\index\controller;
use app\CommonController;
use app\index\middleware\Auth;
use app\index\validate\TradeValidate;
use app\model\FinancialLog;
use app\model\PayCoins;
use app\service\BillSettingService;
use app\service\FinancialLogService;
use app\service\MarketService;
use app\service\MemberCoinService;
use app\service\MemberService;
use app\service\OrderService;
use app\service\PayCoinService;
use think\exception\ValidateException;
use app\model\Market;
use app\model\BillSetting;
use app\model\Member;
class Trade extends CommonController
{
    protected $middleware = [Auth::class];
    public function lists()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post();
            $mid = $this->request->uid;
            $where = [["member_id", "=", $mid]];
            if (!empty($params["status"])) {
                $where[] = ['status', '=', $params["status"]];
            }

            $orderService = $this->app->make(OrderService::class);
            $list = $orderService->getListWithOutCount($where,
                "id,num,profit_percent,is_rise,status,is_win,buy_time,buy_price,sell_price,coin_id,sell_time,time,order_sn,ploss,market_id",
                ["member","coin","market"]
            );
            $content = $this->fetch("trade_ajax", ["list" => $list]);
            $this->result(["data" => $content, "list" => $list]);
        } else {
            return $this->fetch("list");
        }
    }
    public function index()
    {
         $code = $this->request->param("code");
         if (empty($code)) {
             $this->error("参数错误");
         }
         $marketService = $this->app->make(MarketService::class);
         $marketInfo = $marketService->getOne(["code"=>$code,"status"=>Market::MARKET_STATUS_ACTIVE]);
         if (empty($marketInfo)) {
             $this->error("交易币种不存在");
         }
         $billSetting = $this->app->make(BillSettingService::class);
         $billList = $billSetting->getAll(["status"=>BillSetting::BILL_SETTING_STATUS_ACTIVE],"*");
         $memberCoinService = $this->app->make(MemberCoinService::class);
         $payList = $memberCoinService->getListWithOutCount(["member_id"=>$this->request->uid],"*",["coin"]);
         $this->assign(compact("marketInfo","billList",'payList'));
         return $this->fetch("index");
    }

    public function create()
    {
        $params = $this->request->post();
        $coinId = $params["coin_id"];
        $amount = $params["amount"];
        $marketCode= $params["code"];
        $isRise = $params["is_rise"]  ?? 0;
        $marketId = $params["market_id"];
        try {
            validate(TradeValidate::class)->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $control = 0;
        $mid =$this->request->uid;
        $tradeFee = config("global.TRADE_FEE");
        $investmentMin = config("global.INVESTMENT_MIN");
        $profitMid = config("global.PROFIT_MID");
        $profitMids = explode("|",$profitMid);
        if (in_array($mid, $profitMids)) {
            $control = 1;
        }
        $lossMid = config("global.LOSS_MID");
        $lossMids = explode(",",$lossMid);
        if (in_array($mid, $lossMids)) {
            $control = 2;
        }
        $memberService = $this->app->make(MemberService::class);
        $orderService = $this->app->make(OrderService::class);
        $marketService = $this->app->make(MarketService::class);
        $payCoinService = $this->app->make(PayCoinService::class);
        $memberCoinService = $this->app->make(MemberCoinService::class);
        $billService = $this->app->make(BillSettingService::class);
        $financeService = $this->app->make(FinancialLogService::class);
        $billSettingList = $billService->getAll(["status" =>BillSetting::BILL_SETTING_STATUS_ACTIVE]);
        $user = $memberService->get($mid,["audit_status"]);
        if (empty($user)) {
            $this->error("非法的用户");
        }
        if ($user->audit_status!=Member::MEMBER_AUDIT_STATUS_SUCCESS) {
            $this->error("未认证通过");
        }
        if (!$billSettingList) {
            $this->error("跟单未设置");
        }
        $marketInfo = $marketService->getOne(["id"=>$marketId], "id, code, status");
        if (!$marketInfo) {
            $this->error("交易对不存在");
        }
        $marketName = strtoupper($marketInfo['code'] . "/USDT");
        if ( $marketInfo->status == Market::MARKET_STATUS_INACTIVE) {
            $this->error("该交易对已经下架");
        }
        if ($amount < $investmentMin) {
            $this->error("不能小于最低投资额度" . $investmentMin);
        }
        $payCoinInfo = $payCoinService->getOne(["id"=>$coinId,"pay_status"=>PayCoins::PAY_COINS_STATUS_ACTIVE], "id, coin_name, pay_status");
        if (!$payCoinInfo) {
            $this->error("支付渠道不存在");
        }
        $memberCoinInfo = $memberCoinService->getOne(["coin_id" => $coinId, "member_id" => $mid]);
        if (!$memberCoinInfo) {
            $this->error("当前支付渠道没有充值");
        }
        if ($memberCoinInfo->account_amount < $amount) {
            $this->error("当前支付渠道余额不足，请充值或者选择其他支付渠道");
        }
        $costFee = $amount+$tradeFee*$amount/100;
        if ($memberCoinInfo->account_amount<$costFee) {
             $this->error("钱包{$marketName}不足");
        }
        $order = [];
        foreach ($billSettingList as $setting) {
            if (strtotime($setting['buy_time']) < time()) {
                continue;
            }
            $data = [];
            $buytime = date("Y-m-d") . ' ' . $setting['buy_time'];
            $selltime = date("Y-m-d H:i:s", strtotime($buytime) + $setting["sell_interval"] * 60);
            $data["member_id"] = $mid;
            $data["num"] = $amount;
            $data["time"] = 1;
            $data["profit_percent"] = $setting["profit_percent"];
            $data["is_rise"] = $isRise;
            $data["market_id"] =$marketInfo["id"];
            $data["coin_id"] =$coinId;
            $data["buy_time"] = $buytime;
            $data["control"] = $control==0 ? $setting["is_win"]:$control;
            $data["sell_time"] = strtotime($selltime);
            $data["buy_price"] = h_now_price($marketInfo["code"]);
            $order[] = $data;
        }
        if (count($order) == 0) {
            $this->error("交易时间超时");
        }
        $orderService->transaction(function () use ($orderService, $order, $financeService, $amount, $mid, $coinId, $marketName) {
            $orderService->saveAll($order);
            $financeService->flowLog($mid, $amount, $coinId, 0, FinancialLog::TRADE, "购买{$marketName}合约");
        });
        $this->success("购买成功");
    }
}